package com.xhai.admin.service;

import com.xhai.common.domain.entity.SysDept;
import com.xhai.common.domain.entity.SysPost;
import com.xhai.common.domain.login.LoginUser;
import com.xhai.common.exception.ServiceException;
import com.xhai.common.constant.DataConstants;
import com.xhai.common.utils.classes.CollectionUtils;
import com.xhai.common.utils.i18n.MessageUtils;
import com.xhai.common.utils.classes.ObjectUtils;
import com.xhai.common.domain.entity.SysUser;
import com.xhai.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xhai
 * @description 用户验证处理
 * @date 2025/5/29
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysDeptService sysDeptService;

    @Resource
    private SysPostService sysPostService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private PasswordService passwordService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.selectUserByUsername(username);
        if (ObjectUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (ObjectUtils.equals(DataConstants.LOGIC_DEL_FLAG_DELETE, user.getLogicDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (ObjectUtils.equals(DataConstants.STATUS_UNUSED, user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        // 校验密码
        passwordService.validate(user);

        return createLoginUserByUsername(user);
    }

    /**
     * 根据用户信息组装登录用户和权限信息
     *
     * @param user
     * @return
     */
    private UserDetails createLoginUserByUsername(SysUser user) {
        List<SysDept> depts = sysDeptService.selectDeptByUserId(user.getUserId());

        List<SysPost> posts = sysPostService.selectPostByUserId(user.getUserId());

        Set<String> permissions = permissionService.getPermissionByPostIds(posts.stream().map(SysPost::getPostId).collect(Collectors.toSet()));

        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setDepts(depts);
        loginUser.setPosts(posts);
        loginUser.setPermissions(permissions);

        return loginUser;
    }
}
